<template>
  <base-window className="work-flow-approve" :title="$t('common.zhongqi.setApprovalProcess')" size="large" width="800px" :sizeData="{ minWidth: 1060, minHeight: 650 }" :show.sync="isShow">
    <div class="work-flow-frame" v-loading="loading" v-if="isShow">
      <iframe id="paasIframe" ref="iframePage" :src="iframeEditUrl" height="100%" width="100%" @load="onLoad" />
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button @click="isShow = false">{{ $t('common.base.cancel') }}</el-button>
      <el-button :disabled="pending" type="primary" @click="saveWorkFlow">{{ $t('common.base.makeSure') }}</el-button>
    </span>
  </base-window>
</template>
<script>
/** api */
import { reDeployment, updateProcess } from '@src/api/TaskApi.ts';
import { createVipApproveFlow } from '@src/api/SparepartApprove.ts';
/** util */
import { uuid } from '@src/util/lang/string'
import _ from 'lodash';

export default {
  name:'work-flow-dialog',
  data(){
    return {
      isShow: false,
      pending: false,
      loading: true,
      iframeEditUrl: '',
      compId: uuid(),
      paasObj: {
        appId:'',
        formTemplateId:''
      }
    }
  },
  mounted() {
    window.addEventListener('message', this.onMessageCall);
    this.$once('hook:beforeDestroy', () =>  window.removeEventListener('message', this.onMessageCall))
  },
  methods: {
    onLoad() {
      this.loading = false;
      this.pending = false;
    },
    /** 监听数据保存*/
    async onMessageCall(event) {
      try {
        const { data, action, compId, errMsg } = event.data
        // 判断是否是当前组件发起的请求
        if (compId !== this.compId) return;

        // 判断审批节点是否没有选择审批人
        if(errMsg?.length) {
          return this.$alert(errMsg?.join('</br>'), this.$t('common.base.toast'), {
            dangerouslyUseHTMLString: true
          })
        }
        if(action === 'PaaS.frame.returnPaaSWorkflow') {
          const { flowData, currentVersion, nodeStyle } = _.cloneDeep(data)
          this.approveJson = flowData
          let params = {
            antvJson: this.approveJson || {},
            workflowTemplateId: currentVersion?.bizId || '',
            nodeStyle,
            ...this.paasObj
          }

          // 接受paas传过来的参数保存审批数据
          const res = await updateProcess(params)
          if (res.success) {
            this.isShow = false;
            this.$emit('refreshIframe')

            this.$platform.notification({
              title: this.$t('common.base.tip.settingSuccess'),
              type: 'success'
            });
          } else {
            this.$platform.notification({
              title: res.message,
              type: 'error'
            });
          }
        }

      } catch(error){
        console.error('Error in reDeployment:', error);
      } finally {
        this.pending = false;
      }
     
    },

    /** 保存paas流程 */
    saveWorkFlow() {
      if(this.loading) return
      this.pending = true
      let iframe = this.$refs.iframePage.contentWindow;
      let message = {
          action: 'shb.frame.getPaaSWorkflow',
          compId: this.compId
      };
      iframe.postMessage(message, '*')
    },
    /** 打开paas流程弹窗 */
    async openWorkflow(type) {
      try{
        this.isShow = true;
        this.loading = true;
        this.pending = true;
 
        const { code, message, result } = await createVipApproveFlow({ type})
        if(code !== 0) return this.$message.warning(message)
        this.paasObj = result;

        this.iframeEditUrl = `/paas/#/workflow?appId=${this.paasObj.appId}&formId=${this.paasObj.formTemplateId}&moduleType=sparePart&taskFlowType=create`
      }catch(error){
        console.log(error)
      }

    },
    // 已经拼接好的url
    openWorkflowHasUrl(url, passDate) {
      this.isShow = true;
      this.loading = true;
      this.pending = true;

      this.paasObj = passDate;
      this.iframeEditUrl = url
    },
  },
   
}
</script>
<style lang="scss" scoped>
.work-flow-frame {
  width: 100%;
  height: 100%;
}
</style>
<style lang="scss">
.work-flow-approve {
  z-index: 1000 !important;
}
</style>